package com.leecode.string;

/**
 * 字符串中,单词反转
 */
public class ReverseStrMain {
	public static void main(String[] args) {
//		for (String s : "hello   world!".split(" ")) {
//			System.out.println(s);
//		}
		System.out.println(reverseWords("  hello   world! d  "));
	}

	/**
	 * 双指针,学到了
	 */
	public static String reverseWords(String s) {
		String trim = s.trim();
		StringBuilder stringBuilder = new StringBuilder();
		int i = trim.length()-1,j=i;
		while (i >= 0) {
			while(i>=0&&trim.charAt(i)!=' ')i--;
			stringBuilder.append(trim.substring(i + 1, j + 1) + " ");
			while(i>=0&&trim.charAt(i)==' ')i--;
			j=i;
		}
		return stringBuilder.toString().trim();
	}

}
